package com.codding.springboot_mybatisdemo.controller;

import com.codding.springboot_mybatisdemo.entity.Users;
import com.codding.springboot_mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/userController")
public class UserController {
    @Autowired
    private UserService userService;

    // 搜索用户
    @RequestMapping("/doSearch")
    public String doSearch(Integer userId, String userName, String userTel, String userSex,
                           Integer minScore, Integer maxScore, Model model){
        List<Users> users = userService.selectByCondition(userId, userName, userTel, userSex, minScore, maxScore);
        model.addAttribute("userList", users);
        return "select";
    }

    // 删除用户
    @DeleteMapping("/delete/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable int userId) {
        Map<String, Object> response = new HashMap<>();
        boolean success = userService.deleteUserById(userId);
        if (success) {
            response.put("success", true);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    //跳转到注册页面
    @RequestMapping("/goAdd")
    public String goAdd(Model model) {
        return "insert";
    }

    // 添加用户的处理方法
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(@RequestParam("userId") int userId,
                          @RequestParam("userName") String userName,
                          @RequestParam("userScore") int userScore,
                          @RequestParam("userTel") String userTel,
                          @RequestParam("userSex") String userSex,
                          Model model) {
        // 创建用户对象
        Users newUser = new Users(userId, userName, userScore, userTel, userSex);

        // 调用服务层方法保存用户
        boolean success = userService.addUser(newUser);

        // 根据添加结果返回不同的视图
        if (success) {
            // 将添加的用户信息传递到成功页面
            model.addAttribute("userId", userId);
            model.addAttribute("userName", userName);
            model.addAttribute("userScore", userScore);
            model.addAttribute("userTel", userTel);
            model.addAttribute("userSex", userSex);
            return "insertok";  // 插入成功后跳转到成功页面
        } else {
            model.addAttribute("errorMsg", "用户添加失败！");
            return "insert";  // 如果失败，返回添加页面
        }
    }
}
